package communicationMessages;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;

import logger.LoggerWriter;
import database.DB;

public class removeModeratorMessage extends Message {

	@Override
	public String getAnswer() {
		String[] arr = this.content.split(delimiter);
		LoggerWriter logger = LoggerWriter.getLoggerWriter();
		String ans = "";
		if (arr.length != 3)
		{
			logger.log("failed"+delimiter+"removeModerator Message wrong format"+delimiter, Level.WARNING);
			ans = "failed"+delimiter+"removeModerator Message wrong format"+delimiter;
		}
		else
		{
			
			ans = removeModerator(arr, ans);
				
		}
		return ans;
	}

	private String removeModerator(String[] arr, String ans) {
		String userName ,subForumId, moderatorName;
		userName = arr[0];
		subForumId = arr[1];
		moderatorName = arr[2];
		if (DB.isAdmin(userName))
		{
			int moderatorID = DB.getUserId(moderatorName);
			if (moderatorID > 0)
			{
				try
				{
					ResultSet res = DB.getModeratorList(subForumId);
					Vector<String> moderators = getModerators(res);
					if (moderators.size()> 1 && moderators.contains(moderatorName))
					{
						if (DB.notPublishMsgInLastHour(subForumId,moderatorID))
						{
							DB.removeModerator(subForumId,moderatorID);
							ans = "ModeratorsRemoved"+delimiter + "admin"+delimiter+"Success"+delimiter;
						}
						else
						{
							ans = "ModeratorsRemoved"+delimiter + "admin"+delimiter+"Failed"+delimiter;
						}
					}
				}
				catch (SQLException e)
				{
					System.out.println("removeModeratorMessage SQLException " + e.getMessage());
				}
				
			}
		}
		return ans;
	}

	private Vector<String> getModerators(ResultSet res) throws SQLException{
		Vector<String> ans = new Vector<String>();
		while (res.next())
		{
			ans.add(res.getString(1));
		}
		return ans;
	}
	
//	int subForumInt = Integer.valueOf(subForumId);
//	Vector<Integer> path = new Vector<Integer>();
//	path.add(subForumInt);
//	Forum forum = Forum.getForum();
//	SubForum subForum = forum.getSubForum(subForumInt);
//	Boolean answer = subForum.removeModerator(userName, moderatorName);
//	if (answer)
//	ans = "ModeratorsRemoved"+delimiter + MemberDataBase.getUserRoll(userName)+delimiter+"Success"+delimiter;
//	else
//		ans = "ModeratorsRemoved"+delimiter + MemberDataBase.getUserRoll(userName)+delimiter+"Failed"+delimiter;
}
